package com.core.config;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * @Author: 孙常胜
 * @CreateTime: 2021/7/9 10:54
 * @Description:
 */
@Log4j2
@Service
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务端，接收到客户端数据：{}", msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("服务端：有客户端连接成功：{}", ctx.channel());
        //有客户端连接成功
        String result ="服务端你好";
        byte[] req = result.getBytes("UTF-8");
        ByteBuf pingMessage = Unpooled.buffer();
        pingMessage.writeBytes(req);
        ctx.writeAndFlush(pingMessage);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("断开连接：{}", ctx.channel());
        ctx.fireChannelInactive();
    }
}
